<template>
    <div>
        <n-card>
            <n-space style="margin-bottom: 10px">
                <n-input v-model:value="searchWord" placeholder="请输入模型名称" style="width: 300px">
                </n-input>
                <n-input v-model:value="searchModel" placeholder="请输入模型类型" style="width: 300px">
                </n-input>
                <n-button type="primary"  :on-click="getList">查询</n-button>

            </n-space>
        </n-card>
        <n-card style="margin-top: 10px">
            <n-button type="primary" style="margin-bottom: 10px;" @click="modelInfo = null ; downloadModal = !downloadModal">
              C站模型查询
            </n-button>

            <n-button type="primary" style="margin-bottom: 10px;margin-left: 5px;" @click="libModelInfo = null ; liblibDownloadModal = !liblibDownloadModal">
              Lib模型查询
            </n-button>

            <n-data-table
                :columns="columns"
                :data="modelInfoList"
                :loading="tableLoading"
            >
            </n-data-table>
            <n-space justify="end" style="margin-top: 10px">
                <n-pagination
                    :display-order="['quick-jumper', 'pages', 'size-picker']"
                    :item-count="tableTotal"
                    :page-size="paginationReactive.pageSize"
                    :page-sizes="paginationReactive.pageSizes"
                    show-quick-jumper
                    show-size-picker
                    :on-update:page-size="onPageSizeChange"
                    :on-update:page="onPageChange"
                />
            </n-space>
        </n-card>

        <n-modal
            v-model:show="liblibDownloadModal"
            class="custom-card"
            preset="card"
            style=" width:1000px"
            title="模型查询"
            size="huge"
        >
            <n-form ref="formRef" :model="civitaiQueryForm" :style="{ maxWidth: '1000px' }">
                <n-form-item
                    label="查询条件"
                    path="name"
                >
                    <n-input v-model:value="civitaiQueryForm.query" clearable />
                    <n-button style="margin-left: 5px;" type="primary" @click="liblibModelQuery" :loading="proxyLoading">查询</n-button>
                </n-form-item>
              <div v-if="libModelList">
                <n-row>
                    <n-col :span="12">
                      <n-form-item label="模型名称">
                        <n-select
                            label-field="name"
                            value-field="uuid"
                            children-field="whateverChildren"
                            filterable
                            :options="libModelList"
                            :on-update:value="onLibModelChange"
                            :loading="proxyLoading"
                        />
                      </n-form-item>
                    </n-col>

                    <n-col v-if="libModelInfo" :span="12" style="padding-left:10px ">
                      <n-form-item label="请选择版本" path="selectValue">
                        <n-select
                            label-field="name"
                            value-field="name"
                            filterable
                            :options="libModelInfo.versions"
                            :on-update:value="onLibModelVersionChange"
                        />
                        <n-button type="primary" style="margin-left: 5px" @click="libModelImport">导入</n-button>
                      </n-form-item>
                    </n-col>
                </n-row>
               <n-row v-if="libModelInfo">
                  <n-col :span="18">
                      <n-carousel style="height: 350px;" :show-arrow="true" :slides-per-view="3" :space-between="20"  draggable>
                        <img
                            v-for="image in selectModelVersion?.imageGroup?.images"
                            class="carousel-img"
                            :src="image.imageUrl"/>

                      </n-carousel>
                  </n-col>
                  <n-col :span="6">
                      <n-statistic label="模型类型">
                         {{libModelInfo.modelType==1?"checkpoint":libModelInfo.modelType==5?"lora":"未知" }}
                      </n-statistic>

                      <n-statistic label="基础模型">
                        {{libModelInfo.checkpointType==0? "SD 1.5":"SDXL 1.0"}}
                      </n-statistic>

                      <n-statistic label="uid">
                          {{libModelInfo.uuid}}
                      </n-statistic>

                      <n-statistic label="标签">
                          <n-scrollbar style="max-height: 120px">
                            <n-tag v-for="tag in libModelInfo.tags" :key="tag" type="primary">{{tag.tagLabel}}</n-tag>
                          </n-scrollbar>
                      </n-statistic>
                  </n-col>
               </n-row>
<!--               <n-grid cols="4" item-responsive>-->

<!--                   <n-grid-item span="3">-->

<!--                   </n-grid-item>-->
<!--                   <n-grid-item span="1">-->
<!--                       <n-li>模型类型<n-tag type="primary">{{selectModel?.type}}</n-tag></n-li>-->
<!--                       <n-li style="padding-top: 10px;">基础模型<n-tag type="primary">{{selectModelVersion?.baseModel}}</n-tag></n-li>-->
<!--                       <n-li style="padding-top: 10px;">Hash<n-tag type="primary">{{selectModelVersion?.files[0].hashes.AutoV2}}</n-tag></n-li>-->
<!--                   </n-grid-item >-->
<!--               </n-grid>-->
              </div>
            </n-form>
        </n-modal>



      <n-modal
          v-model:show="downloadModal"
          class="custom-card"
          preset="card"
          style=" width:1000px"
          title="模型查询"
          size="huge"
      >
        <n-form ref="formRef" :model="civitaiQueryForm" :style="{ maxWidth: '1000px' }">
          <n-form-item
              label="查询条件"
              path="name"
          >
            <n-input v-model:value="civitaiQueryForm.query" clearable />
            <n-button style="margin-left: 5px;" type="primary" @click="modelQuery" :loading="proxyLoading">查询</n-button>
          </n-form-item>
          <div v-if="modelInfo">
            <n-row>
              <n-col :span="12">
                <n-form-item label="请选择模型" path="selectValue">
                  <n-select
                      label-field="name"
                      value-field="name"
                      children-field="whateverChildren"
                      filterable
                      :options="modelInfo?.items"
                      :on-update:value="onModelChange"
                  />
                </n-form-item>
              </n-col>
              <n-col :span="12" style="padding-left:10px ">
                <n-form-item label="请选择版本" path="selectValue">
                  <n-select
                      label-field="name"
                      value-field="name"
                      children-field="whateverChildren"
                      filterable
                      :options="selectModel?.modelVersions"
                      :on-update:value="onModelVersionChange"
                  />
                  <n-button type="primary" style="margin-left: 5px" @click="modelImprt">导入</n-button>
                </n-form-item>
              </n-col>
            </n-row>
            <n-row>
              <n-col :span="18">
                <n-carousel style="height: 350px;" :show-arrow="true" :slides-per-view="3" :space-between="20"  draggable>
                  <img
                      v-for="image in selectModelVersion?.images"
                      class="carousel-img"
                      :src="image.url"/>

                </n-carousel>
              </n-col>
              <n-col :span="6">
                <n-statistic label="模型类型">
                  {{selectModel?.type}}
                </n-statistic>
                <n-statistic label="基础模型">
                  {{selectModelVersion?.baseModel}}
                </n-statistic>
                <n-statistic label="Hash值">
                  {{selectModelVersion?.files[0].hashes.AutoV2}}
                </n-statistic>
                <n-statistic label="标签">
                  <n-scrollbar style="max-height: 120px">
                    <n-tag v-for="tag in selectModel?.tags" :key="tag" type="primary">{{tag}}</n-tag>
                  </n-scrollbar>
                </n-statistic>
              </n-col>
            </n-row>
            <!--               <n-grid cols="4" item-responsive>-->

            <!--                   <n-grid-item span="3">-->

            <!--                   </n-grid-item>-->
            <!--                   <n-grid-item span="1">-->
            <!--                       <n-li>模型类型<n-tag type="primary">{{selectModel?.type}}</n-tag></n-li>-->
            <!--                       <n-li style="padding-top: 10px;">基础模型<n-tag type="primary">{{selectModelVersion?.baseModel}}</n-tag></n-li>-->
            <!--                       <n-li style="padding-top: 10px;">Hash<n-tag type="primary">{{selectModelVersion?.files[0].hashes.AutoV2}}</n-tag></n-li>-->
            <!--                   </n-grid-item >-->
            <!--               </n-grid>-->
          </div>
        </n-form>
      </n-modal>

      <n-modal v-model:show="txtImage">
        <n-card
            style="width: 1000px"
            title="图片"
            :bordered="false"
            size="huge"
            role="dialog"
            aria-modal="true"
        >
         <n-row>
             <n-col :span="12">
                 <n-image
                     :width="350"
                     :src= selectedPic?.url
                 />
             </n-col>
             <n-col :span="12" v-if="imgPicMetaObj!=null">
                 <n-form>
                     <n-form-item label="Prompt">
                         <n-input type="textarea" :value="imgPicMetaObj.prompt">
                         </n-input>
                     </n-form-item>
                     <n-form-item label="Negative prompt">
                         <n-input type="textarea" :value="imgPicMetaObj.negativePrompt">
                         </n-input>
                     </n-form-item>

                     <n-form-item label="Sampler">
                         <n-input  :value="imgPicMetaObj.sampler">
                         </n-input>
                     </n-form-item>
                     <n-row>
                         <n-col :span="12">
                             <n-form-item label="CFG scale">
                                 <n-input  :value="imgPicMetaObj.cfgScale">
                                 </n-input>

                             </n-form-item>
                         </n-col>
                         <n-col :span="11" style="margin-left: 5px">
                             <n-form-item label="Steps">
                                 <n-input  :value="imgPicMetaObj.steps">
                                 </n-input>

                             </n-form-item>
                         </n-col>
                     </n-row>
                     <n-row>
                         <n-col :span="12">
                             <n-form-item label="Seed">
                                 <n-input  :value="imgPicMetaObj.seed">
                                 </n-input>
                             </n-form-item>
                         </n-col>
                         <n-col :span="11" style="margin-left: 5px">
                             <n-form-item label="Clip skip">
                                 <n-input  :value="imgPicMetaObj.clipSkip">
                                 </n-input>
                             </n-form-item>
                         </n-col>
                     </n-row>
                     <n-button block type="primary">复制</n-button>
                 </n-form>
             </n-col>
         </n-row>
        <n-space style="margin-top:20px" >
            <n-scrollbar  x-scrollable style="max-height: 130px">
                <div style="white-space: nowrap;" >
                    <n-image v-for="image in modelImageList"
                             preview-disabled
                             :lazy="true"
                             :height="80"
                             size="small"
                             @click="selectedPic = image ; imgPicMetaObj=JSON.parse(image.meta)"
                             :class="{ 'selected': image.url == selectedPic?.url }"
                             style="margin-left: 10px;"
                             :src=image.url
                    />
                </div>
            </n-scrollbar>
        </n-space>

        </n-card>
      </n-modal>
    </div>
</template>

<script lang="ts" setup>
import {computed, h, onMounted, reactive, ref} from 'vue'
import {NButton, NTag,useNotification,NotificationType} from "naive-ui";
//@ts-ignore
import Bus from '@/components/file/box/GlobalUploader/utils/bus.js'
import {civitaiController} from '@/api/controller/civitai/civitaiController'
const modelInfoList = ref<Array<any>>([])
const searchWord = ref('')
const searchModel = ref('')

const tableLoading = ref(false)
const downloadModal = ref(false)
const liblibDownloadModal = ref(false)
const formRef = ref(null)
const proxyLoading = ref(false)
const modelInfo = ref(null)
const libModelInfo = ref(null)

const libModelList =ref<Array<any>>([])


const notification = useNotification()
const txtImage = ref(false)
const modelImageList = ref(null)
const selectModel = ref(null)
const selectModelVersion = ref(null)
const selectedPic = ref()

const civitaiQueryForm = reactive({
    query:''
})


const tableTotal = ref(0)
const paginationReactive = reactive({
    page: 1,
    pageSize: 5,
    pageSizes: [5,10]
})


const imgPicMetaObj = ref()

const onPageSizeChange = (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    getList()

}

const onPageChange = (page: number) => {
    paginationReactive.page = page
    getList()
}

onMounted(()=>{
    getList()
})
const getList = () =>{
    tableLoading.value = true
    const data = {
        modelName : searchWord.value,
        modelType : searchModel.value

    }
    civitaiController.modelList(data,{
        page: paginationReactive.page,
        pageSize: paginationReactive.pageSize
    }).then((res)=>{
        tableLoading.value = false
        if(res.code === 200){
            modelInfoList.value = res.data.list
            tableTotal.value = res.data.count
            const key = ref(0)
            modelInfoList.value.forEach((item)=>{
                item.key = key.value
                key.value = key.value +1
            })
        }
    }).catch((e: any) => {
        tableLoading.value = true
    })
}

const liblibModelQuery = () =>{
    if(civitaiQueryForm.query.length > 0){
        proxyLoading.value = true
        civitaiController.libModelQuery(civitaiQueryForm.query).then( res =>{
            proxyLoading.value = false
            if(res.code === 200){
              const jo = JSON.parse(res.data)
              console.log(jo)
              if (jo){
                libModelList.value = jo.data.data
              }
              console.log(libModelList.value)
              // libModelInfo.value = JSON.parse(res.data)
              // console.log(libModelInfo.value)
            }
        })
    }
}

const modelQuery = () => {
  if(civitaiQueryForm.query.length > 0){
    proxyLoading.value = true
    civitaiController.modelQuery(civitaiQueryForm.query).then( res =>{
      proxyLoading.value = false
      if(res.code === 200){
        modelInfo.value = JSON.parse(res.data)
      }
    })
  }
}


const onModelChange = (value:any,option:any) =>{
    selectModel.value = option
}

const onLibModelChange = (value:any,option:any) =>{
  searchLibModel(value)
}

const onLibModelVersionChange = (value:any,option:any) =>{
  selectModelVersion.value = option
}

const onModelVersionChange = (value:any,option:any) =>{
    selectModelVersion.value = option
}


const libModelImport = ()=>{
  const civitaiImage = []
  console.log(selectModelVersion.value)
  selectModelVersion.value.imageGroup.images.forEach((item:any) =>{
    civitaiImage.push({
      url:item.imageUrl,
      meta:JSON.stringify(item.generateInfo),
      nsfw:'None'
    })
  })

  const tags_a = []
  console.log(libModelInfo.value)
  libModelInfo.value.tags.forEach((item:any) =>{
    tags_a.push(item.tagLabel)
  })

  const civitaiModel = {
    modelName: libModelInfo.value.name,
    modelVersion: selectModelVersion.value.name,
    modelType: libModelInfo.value.modelType==1?"Checkpoint":libModelInfo.value.modelType==5?"Lora":"未知",
    baseModel: libModelInfo.value.checkpointType==0? "SD 1.5":"SDXL 1.0",
    hashCode:  selectModelVersion.value.uuid,
    tags: tags_a,
    fileName : selectModelVersion.value.attachment.modelSourceName,
    images: civitaiImage,
    sourceName: "liblib"
  }
  civitaiController.modelImport(civitaiModel).then(res =>{
    if(res.code === 200){
      notification.success({
        title: '导入成功',
        message: '导入成功',
        duration: 2000
      })
    }
  })
}

const searchLibModel = (uuid:string) =>{
  proxyLoading.value = true
  civitaiController.searchLibModel(uuid).then( res =>{
    if(res.code === 200){
       const json = JSON.parse(res.data)
      console.log(libModelInfo.value)
      libModelInfo.value = json.data
    }
  }).finally(()=>{
    proxyLoading.value = false
  })
}


const modelImprt = () =>{
    const civitaiImage = []
    selectModelVersion.value.images.forEach((item:any) =>{
        civitaiImage.push({
            url:item.url,
            meta:JSON.stringify(item.meta),
            nsfw:item.nsfw
        })
    })
    const civitaiModel = {
        modelName: selectModel.value.name,
        modelVersion: selectModelVersion.value.name,
        modelType: selectModel.value.type,
        baseModel: selectModelVersion.value.baseModel,
        hashCode:  selectModelVersion.value.files[0].hashes.AutoV2,
        tags: selectModel.value.tags,
        fileName : selectModelVersion.value.files[0].name,
        images: civitaiImage
    }
    civitaiController.modelImport(civitaiModel).then(res =>{
        if(res.code === 200){
            notification.success({
                title: '导入成功',
                message: '导入成功',
                duration: 2000
            })
        }
    })
}

const showImage = (row:any) =>{
    // 查看文本
    txtImage.value = true
    civitaiController.imageList({modelId:row.id}).then((res)=>{
        if(res.code === 200){
            console.log(res.data)
            modelImageList.value = res.data
        }
    })

}


const columns = [
    {
        type: 'expand',
        renderExpand: (rowData:any) => {
            const tags = []
            rowData.tags.split(",").forEach((item:any) =>{
                tags.push(h(NTag,
                    {
                            type:'primary'
                          },
                    {default: () => item}))
            })
            return tags
        }
    },{
        title: '名称',
        key: 'modelName'
    },{
        title: '版本',
        key: 'modelVersion'
    },{
        title: '类型',
        key: 'modelType'
    },{
        title: '基础模型',
        key: 'baseModel'
    },{
        title: '模型文件名称',
        key: 'fileName'
    },{
        title: 'hash值',
        key: 'hashCode'
    } ,
    {
        title: '操作',
        key: 'address',
        render (rowData:any) {
            const buttons = [];
            buttons.push(h(
                NButton,
                {
                    size: 'small',
                    type: 'primary',
                    onClick: () => {
                       showImage(rowData)
                    }
                },
                {default: () => '查看'}
            ))
            return buttons
        }
    }
]
</script>
<style scoped>
.carousel-img {
  width: 90%;
  height: 300px;
  object-fit: cover;
}
.selected {
    border: 3px solid #8250df;
}
</style>
